/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package program.gui;

import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import program.beans.Company;
import program.database.Database;

/**
 * A Dialog where the user can choose a company which are read from the
 * database. Companies can also be added, edited or deleted.
 *
 * Responsible: Patrick, Bernhard
 */
public class ChooseCompanyDlg extends javax.swing.JDialog {

    private Company selectedCompany;
    private boolean ok;
    private Vector<Company> allCompanies = new Vector<>();
    private Vector<Company> shownCompanies = new Vector<>();
    private Database db = Database.getDatabase();

    /**
     * Creates new form ChooseCompanyDlg
     */
    public ChooseCompanyDlg(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        setLocationRelativeTo(null);
        initList(-1);
    }

    /**
     * Read all companies from Database and store them into the Collections.
     * Show them on the GUI.
     * Select the right company in list.
     *
     * @param selectedIndex The index of the item which should be selected
     */
    private void initList(int selectedIndex) {
        allCompanies.clear();
        shownCompanies.clear();
        try {
            allCompanies.addAll(db.getAllCompanies());
        } catch (Exception ex) {
                        JOptionPane.showMessageDialog(null, ex);

        }
        shownCompanies.addAll(allCompanies);

        if (shownCompanies.size() > 0) {
            selectedCompany = selectedIndex == -1 ? shownCompanies.firstElement() : getSelectedCompany(selectedIndex);
        }
        liCompanies.setListData(allCompanies);
        liCompanies.setSelectedValue(selectedCompany, false);
        tfSelectedCompany.setText("");
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        tfSelectedCompany = new javax.swing.JTextField();
        pnCenter = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        liCompanies = new javax.swing.JList();
        pnButtons = new javax.swing.JPanel();
        btAdd = new javax.swing.JButton();
        btChange = new javax.swing.JButton();
        btDelete = new javax.swing.JButton();
        pnBottom = new javax.swing.JPanel();
        btOk = new javax.swing.JButton();
        btCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Firma auswählen");

        tfSelectedCompany.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                onUpdateList(evt);
            }
        });
        getContentPane().add(tfSelectedCompany, java.awt.BorderLayout.PAGE_START);

        pnCenter.setLayout(new java.awt.BorderLayout());

        liCompanies.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        liCompanies.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                onSelectItem(evt);
            }
        });
        jScrollPane2.setViewportView(liCompanies);

        pnCenter.add(jScrollPane2, java.awt.BorderLayout.CENTER);

        pnButtons.setLayout(new java.awt.GridBagLayout());

        btAdd.setText("hinzufügen");
        btAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onAddCompany(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.insets = new java.awt.Insets(15, 0, 15, 0);
        pnButtons.add(btAdd, gridBagConstraints);

        btChange.setText("bearbeiten");
        btChange.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onEditCompany(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new java.awt.Insets(15, 0, 15, 0);
        pnButtons.add(btChange, gridBagConstraints);

        btDelete.setText("entfernen");
        btDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onDeleteCompany(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(15, 0, 15, 0);
        pnButtons.add(btDelete, gridBagConstraints);

        pnCenter.add(pnButtons, java.awt.BorderLayout.LINE_END);

        getContentPane().add(pnCenter, java.awt.BorderLayout.CENTER);

        pnBottom.setLayout(new java.awt.GridBagLayout());

        btOk.setText("OK");
        btOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onOk(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 10);
        pnBottom.add(btOk, gridBagConstraints);

        btCancel.setText("Abbrechen");
        btCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onCancel(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 10);
        pnBottom.add(btCancel, gridBagConstraints);

        getContentPane().add(pnBottom, java.awt.BorderLayout.PAGE_END);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * KeyReleased event for the textfield (which is always focused) 
     * If Key is 'enter', call ok event 
     * If Key is 'esc', call cancel event
     * If Key is 'up', select item above in list
     * If Key is 'down', select item below in list 
     * Else retreive the items which fit to the entry in the textfield
     *
     * @param evt KeyEvent
     */
    private void onUpdateList(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_onUpdateList
        if (evt.getKeyCode() == 10) { // Enter
            onOk(null);
        } else if (evt.getKeyCode() == 27) { //Esc
            onCancel(null);
        } else if (evt.getKeyCode() == 38) { // Up
            int index = shownCompanies.indexOf(selectedCompany);
            index = index > 0 ? index - 1 : index;
            selectedCompany = shownCompanies.elementAt(index);
        } else if (evt.getKeyCode() == 40) { // Down
            int index = shownCompanies.indexOf(selectedCompany);
            index = index < shownCompanies.size() - 1 ? index + 1 : index;
            selectedCompany = shownCompanies.elementAt(index);
        } else {
            String curEntry = tfSelectedCompany.getText();
            shownCompanies.clear();
            if (curEntry.length() == 0) {
                shownCompanies.addAll(allCompanies);
            } else {
                for (Company c : allCompanies) {
                    if (compare(c.getName(), curEntry)) {
                        shownCompanies.add(c);
                    }
                }

                if (!shownCompanies.isEmpty() && !selectedCompany.isIn(shownCompanies)) {
                    selectedCompany = shownCompanies.firstElement();
                }
            }
            liCompanies.setListData(shownCompanies);
        }
        liCompanies.setSelectedValue(selectedCompany, false);
    }//GEN-LAST:event_onUpdateList

    /**
     * Mouse event for the list Change the selected item
     *
     * @param evt KeyEvent
     */
    private void onSelectItem(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_onSelectItem
        selectedCompany = (Company) liCompanies.getSelectedValue();
        tfSelectedCompany.requestFocusInWindow();
    }//GEN-LAST:event_onSelectItem

    /**
     * Set dialog-control-variable true
     * The selected company can now be retrieved by the parent component
     *
     * @param evt ButtonEvent
     */
    private void onOk(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onOk
        if (!shownCompanies.isEmpty()) {
            ok = true;
            dispose();
        } else {
            JOptionPane.showMessageDialog(this, "Keine Firma ausgewählt!");
        }

    }//GEN-LAST:event_onOk

    /**
     * Set dialog-control-variable false
     *
     * @param evt ButtonEvent
     */
    private void onCancel(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onCancel
        ok = false;
        dispose();
    }//GEN-LAST:event_onCancel

    /**
     * Call a dialog to find out the name of the company, which should be added
     * Store the new company in database
     * Reinitialize list
     *
     * @param evt ButtonEvent
     */
    private void onAddCompany(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onAddCompany
        TextInputDlg dlg = new TextInputDlg(this, true, "Firma hinzufügen", "");
        dlg.setVisible(true);
        if (dlg.isOk()) {
            int selectedIndex = 0;
            try {
                selectedIndex = db.addCompany(dlg.getText());
            } catch (Exception ex) {
                         JOptionPane.showMessageDialog(null, ex);

            }
            initList(selectedIndex);
        }
        tfSelectedCompany.requestFocusInWindow();
    }//GEN-LAST:event_onAddCompany

    /**
     * Call a dialog to find out the new name of the selected company
     * Update the edited company in database
     * Reinitialize list
     *
     * @param evt ButtonEvent
     */
    private void onEditCompany(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onEditCompany
        if (!shownCompanies.isEmpty()) {
            TextInputDlg dlg = new TextInputDlg(this, true, "Firma bearbeiten", selectedCompany.getName());
            dlg.setVisible(true);
            if (dlg.isOk()) {
                try {
                    db.editCompany(new Company(selectedCompany.getId(), dlg.getText()));
                } catch (Exception ex) {
                               JOptionPane.showMessageDialog(null, ex);

                }
                initList(selectedCompany.getId());
            }
            tfSelectedCompany.requestFocusInWindow();
        } else {
            JOptionPane.showMessageDialog(this, "Keine Firma ausgewählt!");
        }
    }//GEN-LAST:event_onEditCompany

    /**
     * Delete the selected company in database 
     * Reinitialize list
     *
     * @param evt ButtonEvent
     */
    private void onDeleteCompany(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onDeleteCompany
        if (!shownCompanies.isEmpty()) {
            try {
                db.deleteCompany(selectedCompany.getId());
            } catch (Exception ex) {
                            JOptionPane.showMessageDialog(null, ex);

            }
            initList(-1);
            tfSelectedCompany.requestFocusInWindow();
        } else {
            JOptionPane.showMessageDialog(this, "Keine Firma ausgewählt!");
        }
    }//GEN-LAST:event_onDeleteCompany

    /**
     * Check if stringPart is similar to the first letters of wholeString
     *
     * @param wholeString The string in which the other string should be
     * @param stringPart The string which should be similar to the first or all
     * letters of wholeString
     * @return True if the stringPart is similar to the first or all letters of
     * wholeString
     */
    private boolean compare(String wholeString, String stringPart) {
        if (stringPart.length() > wholeString.length()) {
            return false;
        }
        for (int i = 0; i < stringPart.length(); i++) {
            if (Character.toLowerCase(stringPart.charAt(i)) != Character.toLowerCase(wholeString.charAt(i))) {
                return false;
            }
        }

        return true;
    }

    /**
     * Returns company with the delivered company id
     *
     * @param compid company-id for company which will be returned
     * @return company with the delivered id
     */
    private Company getSelectedCompany(int compid) {
        for (Company c : shownCompanies) {
            if (c.getId() == compid) {
                return c;
            }
        }
        return null;
    }

    /**
     * Returns selected company for the parent component
     *
     * @return The selected company
     */
    public Company getSelectedCompany() {
        return selectedCompany;
    }

    /**
     * Returns dialog-control-variable for the parent component
     *
     * @return dialog-control-variable
     */
    public boolean isOk() {
        return ok;
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAdd;
    private javax.swing.JButton btCancel;
    private javax.swing.JButton btChange;
    private javax.swing.JButton btDelete;
    private javax.swing.JButton btOk;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JList liCompanies;
    private javax.swing.JPanel pnBottom;
    private javax.swing.JPanel pnButtons;
    private javax.swing.JPanel pnCenter;
    private javax.swing.JTextField tfSelectedCompany;
    // End of variables declaration//GEN-END:variables
}
